/**
 * @Authors
 * Avinash Sridhar	G Number: G00861300
 * Martin Nguyen	G Number: G00396532
 * Jitin Krishnan	G Number: G00834757
 * 
 * @Course
 * CS571 Operating Systems Fall 2013
 * Assignment 3
 * Due: Dec 2, 2013 
 * Instructor: Hakan Aydin
 * 
 * Filename: Timer.java
 * 
 **/

/*
 * usage----------
 * Start timer
 * 
 * Timer timer = new Timer(3000);
 * timer.start();
 * 
 * Reset the timer
 * 
 *timer.reset();
 * 
 * 
 */

//test 


public class Timer extends Thread
{
	/** Rate at which timer is checked */
	protected int m_rate = 50;
	
	/** Length of timeout */
	private int m_length;

	/** Time elapsed */
	private int m_elapsed;

	/**
	  * Creates a timer of a specified length IN MILLISECONDS
	  * @param	length	Length of time before timeout occurs
	  */
	public Timer ( int length )
	{
		// Assign to member variable
		m_length = length;

		// Set time elapsed
		m_elapsed = 0;
	}

	
	/** Resets the timer back to zero */
	public synchronized void reset()
	{
		m_elapsed = 0;
	}

	/** Performs timer specific code */
	public void run()
	{
		// Keep looping
		for (;;)
		{
			// Put the timer to sleep
			try
			{ 
				Thread.sleep(m_rate);
			}
			catch (InterruptedException ioe) 
			{
				continue;
			}

			// Use 'synchronized' to prevent conflicts
			synchronized ( this )
			{
				// Increment time remaining
				m_elapsed += m_rate;

				// Check to see if the time has been exceeded
				if (m_elapsed > m_length)
				{
					// Trigger a timeout
					timeout();
				}
			}

		}
	}

	// Override this to provide custom functionality
	public void timeout()
	{
		System.err.println ("Network timeout occurred.... terminating");
		System.exit(1);
	}
	
	public void add(int length){
		this.m_length = this.m_length + length;
	}
}
